﻿using Manon.Core.Commons;
using Manon.Core.Exception;
using Manon.Core.Extensions;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.Extensions.Logging;
using System.Threading.Tasks;

namespace Manon.Core.Filters
{
    public class ApiExceptionAsyncFilter : IAsyncExceptionFilter
    {
        private readonly ILogger<ApiExceptionAsyncFilter> _logger;

        public ApiExceptionAsyncFilter(ILogger<ApiExceptionAsyncFilter> logger)
        {
            _logger = logger;
        }


        /// <summary>
        /// 重写OnExceptionAsync方法，定义自己的处理逻辑
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public Task OnExceptionAsync(ExceptionContext context)
        {
            if (context.ExceptionHandled == false)
            {
                string methodInfo = $"{context.RouteData.Values["controller"] as string}Controller.{context.RouteData.Values["action"] as string}:{context.HttpContext.Request.Method}";

                _logger.LogError(context.Exception, "执行{0}时发生错误！", methodInfo);

                
                context.Result = new JsonResult(null)
                {
                    StatusCode = (int)StateCode.Ok,
                    Value = ApiResult.ErrorResult(context)
                };


            }
            return Task.CompletedTask;
        }


    }
}
